<template>
    <a-drawer popup-container="#wrap" width="100%" :footer="false" :visible="show" :ok-loading="form.loading"
        @cancel="show = false">
        <template #title>
            {{ $t('components.playback.60zelfaja300') }}
        </template>
        <div class="box" v-loading="form.loading">
            <div class="playback">
                <div class="info" v-if="latestPoint?.uavBasic?.id">
                    <div class="info-title">{{ $t('components.playback.60zekq5nwb81') }}</div>
                    <div class="info-demo">
                        <div>
                            <div class="name">{{ $t('components.spect.61lhlwegzo01') }}：</div>
                            <div>{{ latestPoint?.whiteUav?.uavNum ? latestPoint?.whiteUav?.uavNum : '暂未实名认证' }}</div>
                        </div>
                        <div v-if="latestPoint.whiteUav.uavNum">
                            <div class="name">{{ $t('components.playback.60zekq5nwb84') }}：</div>
                            <div>{{ latestPoint?.uavBasic?.id }}</div>
                        </div>
                        <div v-if="latestPoint.whiteUav.uavNum">
                            <div class="name">{{ $t('components.playback.60zekq5nwb85') }}：</div>
                            <div>{{ latestPoint?.whiteUav?.customerName ? latestPoint?.whiteUav?.customerName : '暂未实名认证'
                                }}
                            </div>
                        </div>
                        <div v-if="latestPoint.whiteUav.uavNum">
                            <div class="name">{{ $t('components.playback.60zekq5nwb86') }}：</div>
                            <div>{{ latestPoint?.whiteUav?.idCardNum ? latestPoint?.whiteUav?.idCardNum : '暂未实名认证' }}
                            </div>
                        </div>
                        <div v-if="latestPoint.whiteUav.uavNum">
                            <div class="name">{{ $t('components.playback.60zekq5nwb87') }}：</div>
                            <div>{{ latestPoint?.whiteUav?.address ? latestPoint?.whiteUav?.address : '暂未实名认证' }}</div>
                        </div>
                        <div v-if="latestPoint.whiteUav.uavNum">
                            <div class="name">{{ $t('components.playback.60zekq5nwb88') }}：</div>
                            <div>{{ latestPoint?.whiteUav?.mobile ? latestPoint?.whiteUav?.mobile : '暂未实名认证' }}</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.playback.60zekq5nwb80') }}：</div>
                            <div>
                                <span>{{ useIdModelFormat(latestPoint.uavBasic.id).name }}</span>
                                <!-- <span v-if="info?.uavBasic?.uavType === 1">{{ $t('components.spect.60zduu0v7gc0')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 2">{{ $t('components.spect.60zduu0v7wo0')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 3">{{ $t('components.spect.60zduu0v87o0')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 4">{{ $t('components.spect.60zduu0v8j00')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 5">{{ $t('components.spect.60zduu0v8us0')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 6">{{ $t('components.spect.60zduu0v91w0')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 7">{{ $t('components.spect.60zduu0v9r00')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 8">{{ $t('components.spect.60zduu0v9z80')
                                }}</span>
                            <span v-else-if="info?.uavBasic?.uavType === 9">{{ $t('components.spect.60zduu0va740')
                                }}</span>
                            <span v-else>{{ $t('components.spect.60zduu0vadk0') }}</span> -->
                            </div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.60zduu0v1x47') }}：</div>
                            <div>{{ latestPoint?.rssi }}</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.60zdu10vax47') }}：</div>
                            <div>{{ Math.abs(latestPoint?.uavLocation?.height) }}m</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.60zdu00vax47') }}：</div>
                            <div>{{ latestPoint?.uavLocation?.speedV }}m/s</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.60zdu00vax87') }}：</div>
                            <div>{{ latestPoint?.uavLocation?.speedH }}m/s</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.60zdu00vax88') }}：</div>
                            <div>{{ (getDistances(latestPoint?.uavLocation.lon,
                                latestPoint?.uavLocation.lat,
                                latestPoint?.uavOperatorInfo.lon,
                                latestPoint?.uavOperatorInfo.lat)) }}</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.60zdu00vax80') }}：</div>
                            <div>{{
                                Number(latestPoint?.uavLocation.lon.toFixed(4)) }},{{
                                    Number(latestPoint?.uavLocation.lat.toFixed(4)) }}</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.61lhlwegzo11') }}：</div>
                            <div>{{
                                Number(latestPoint?.uavOperatorInfo.lon.toFixed(4)) }},{{
                                    Number(latestPoint?.uavOperatorInfo.lat.toFixed(4)) }}</div>
                        </div>
                        <div>
                            <div class="name">{{ $t('components.spect.61lhlwegzo12') }}：</div>
                            <div>{{ latestPoint?.uavOperatorInfo.alit }}m</div>
                        </div>
                    </div>
                </div>
                <div class="track" id="track" v-if="form.list?.length"></div>
                <cNone v-if="!form.list?.length"></cNone>
                <div class="play-control" v-if="form.list?.length">
                    <div class="button">
                        <a-button shape="circle" type="primary" @click="start()" v-if="!play">
                            <template #icon>
                                <icon-play-arrow />
                            </template>
                        </a-button>
                        <a-button shape="circle" type="primary" @click="end()" v-else>
                            <template #icon>
                                <icon-pause />
                            </template>
                        </a-button>
                    </div>
                    <div class="play-progress">
                        <a-slider style="width: 300px;margin-right: 30px;" :max="form.list?.length - 1"
                            v-model="progressIndex">
                            <template #mark="{ label, point }">
                                <template v-if="point === form.list?.length">
                                    <strong>{{ label }}</strong>
                                </template>
                                <template v-else>{{ label }}</template>
                            </template>
                        </a-slider>
                        <div class="progress-value">
                            <span>{{ ((progressIndex) / (form.list?.length - 1) * 100 || 0).toFixed(2) }}%</span>
                            /
                            <span>100.00%</span>
                        </div>
                    </div>
                    <!-- 动画控制倍速 -->
                    <div class="progressDiv_speedDiv">
                        <a-select placeholder="倍速" @change="start" v-model="speedVal" size="mini">
                            <a-option v-for="(item, index) in speedCountArr" :value="item.value" :key="index">{{
                                item.name }}</a-option>
                        </a-select>
                    </div>
                    <!-- 跟踪无人机 -->
                    <div class="tail-after">
                        <span>跟踪无人机</span><a-switch v-model="tailAfter" />
                    </div>
                </div>
            </div>
            <div class="footer" v-if="form.list?.length">
                <div style="display: flex;justify-content: end;">
                    <a-button type="primary" @click="show = false">{{ $t('components.playback.60zelfajbcg0')
                        }}</a-button>
                </div>
            </div>
        </div>
    </a-drawer>
</template>

<script lang='ts' setup>
import { PointLayer, LineLayer, Scene } from '@antv/l7'
import { GaodeMap } from '@antv/l7-maps';
import { apiSpectTrack } from '@/api/index'
const show = defineModel('show', { default: false })
const detail: any = defineModel('data', { default: {} })
import { useIdModelFormat } from "@/hooks/comparison";
import { getDistances } from "@/hooks/distance";
const emit = defineEmits(['refresh'])
const local = useLocal()
const form = reactive({
    loading: false,
    mounted: false,
    data: {} as any,
    detail: {} as any,
    points: [] as any,
    list: [] as any,
    uavOperatorInfo: {} as any
})
const getData = async () => {
    form.loading = true
    const { code, data } = await apiSpectTrack({
        uid: local.usermsg.id == 3 ? 0 : local.usermsg.id,
        deviceSn: form.data.uavBasic.id,/*  */
        startTime: form.data.startTime,
        endTime: form.data.endTime,
    })
    form.loading = false
    if (code != 200) return
    form.list = useUniqueByFields(data.list?.filter((item: any) => !!item?.uavLocation?.lat), 'uavLocation.lat', 'uavLocation.lon')
    if (!form.list?.length) return
    nextTick(() => {
        init()
    })
}
// 倍数
const speedCountArr = reactive([
    {
        name: '0.5X',
        value: 0.5,
    },
    {
        name: '0.75X',
        value: 0.75,
    },
    {
        name: '1.0',
        value: 1.0,
    },
    {
        name: '1.25X',
        value: 1.25,
    },
    {
        name: '1.5X',
        value: 1.5,
    },
    {
        name: '1.75X',
        value: 1.75,
    },
    {
        name: '2.0X',
        value: 2.0,
    },
    {
        name: '2.5X',
        value: 2.5,
    },
    {
        name: '3.0X',
        value: 3.0,
    },
])
const play = ref(0)
const progressIndex = ref(0)
const progressList = computed(() => {
    return form.list.filter((_: any, i: number) => i <= progressIndex.value)
})
const latestPoint = computed(() => {
    return progressList.value[progressList.value?.length - 1]
})
const scene = ref()
const bubbleLayer = ref()
const lineLayer = ref()
const pointLayer = ref()
const operatorPointLayer = ref()
const init = () => {
    destroy()
    scene.value = new Scene({
        id: 'track',
        map: new GaodeMap({
            style: local.theme == 'light' ? 'normal' : local.theme,
            token: 'local.mapKey.aMap',
            pitch: 45,
            zoom: 10,
            plugin: ['AMap.MoveAnimation', 'AMap.Polyline'],
        }),
        logoVisible: false,
    });
    scene.value.addImage(
        '00',
        '/pilot.svg',
    );
    scene.value.addImage(
        '01',
        '/spect.svg',
    );
    scene.value?.on('loaded', () => {
        console.log('loaded')
        createLineLayer()
        createLayer()
    })

}
const createLineLayer = () => {
    scene.value && bubbleLayer.value && scene.value.removeLayer(bubbleLayer.value)
    scene.value && lineLayer.value && scene.value.removeLayer(lineLayer.value)
    if (!scene.value || !form.list?.length) return;
    // 3d气泡
    bubbleLayer.value = new PointLayer({
        zIndex: 2,
        autoFit: true //自动铺满
    })
        .source({
            features: form.list.map((item: any) => {
                return {
                    type: "Feature",
                    properties: {
                        id: item.uavBasic.id,
                        mag: 2.3,
                        time: 1507425650893,
                        felt: null,
                        tsunami: 0,
                        color: item.color,
                    },
                    geometry: {
                        type: "Point",
                        coordinates: [
                            Number(item.uavLocation.lon), Number(item.uavLocation.lat), Number(item.uavLocation.height)
                        ]
                    }
                }
            }),
            type: "FeatureCollection",
            crs: {
                type: "name",
                properties: {
                    name: "urn:ogc:def:crs:OGC:1.3:CRS84"
                }
            }
        })
        .shape('simple')
        .size(20)
        .color('mag', (mag) => {
            return mag > 4.5 ? '#5B8FF9' : '#5CCEA1';
        })
        .animate({
            interval: 1, // 间隔
            duration: 1, // 持续时间，延时
            trailLength: 2, // 流线长度
        })
        .style({
            opacity: 0.6,
            strokeWidth: 2,
            stroke: '#38FFF2'
        });


    // 轨迹
    lineLayer.value = new LineLayer({
        zIndex: 1
    })
        .source({
            type: "FeatureCollection",
            name: "tw",
            crs: {
                type: "name",
                properties: {
                    name: "urn:ogc:def:crs:OGC:1.3:CRS84"
                }
            },
            features: [
                {
                    type: "Feature",
                    properties: {},
                    geometry: {
                        type: "LineString",
                        coordinates: form.list.map((item: any) => [
                            Number(item.uavLocation.lon), Number(item.uavLocation.lat), Number(item.uavLocation.height)
                        ])
                    }
                }
            ]
        })
        .size(2)
        .shape('line')
        .style({
            vertexHeightScale: 8,
            speed: 2,
        })
        .animate({
            interval: 1, // 间隔
            duration: 1, // 持续时间，延时
            trailLength: 2, // 流线长度
        })
        .color('#FFFC38');
    scene.value.addLayer(bubbleLayer.value);
    scene.value.addLayer(lineLayer.value);
}
let tailAfter = ref(false)
const createLayer = () => {

    pointLayer.value && scene.value && scene.value.removeLayer(pointLayer.value)
    operatorPointLayer.value && scene.value && scene.value.removeLayer(operatorPointLayer.value)
    if (!scene.value || !progressList.value?.length) return
    // 无人机定位
    pointLayer.value = new PointLayer({
        zIndex: 3
    })
        .source({
            type: "FeatureCollection",
            crs: {
                type: "name",
                properties: {
                    name: "urn:ogc:def:crs:OGC:1.3:CRS84"
                }
            },
            features: [
                {
                    "type": "Feature",
                    "properties": {

                    },
                    "geometry": {
                        "type": "Point",
                        "coordinates": [
                            latestPoint.value?.uavLocation?.lon,
                            latestPoint.value?.uavLocation?.lat
                        ]
                    }
                }
            ]
        })
        .shape('01')
        .size(15)
        .style({
            raisingHeight: latestPoint.value?.uavLocation?.height * 8,
            heightfixed: true
        })
    operatorPointLayer.value = new PointLayer({
        zIndex: 2,
    }).source(
        [
            {
                lng: latestPoint.value?.uavOperatorInfo?.lon,
                lat: latestPoint.value?.uavOperatorInfo?.lat
            }
        ]
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                // zoomOffset: 1,
            },
        })
        .shape('00')
        .size(15);
    scene.value.addLayer(pointLayer.value);
    scene.value.addLayer(operatorPointLayer.value)
    tailAfter.value && scene.value.setCenter([latestPoint.value?.uavLocation?.lon, latestPoint.value?.uavLocation?.lat])
}
useWatch(show, (val: boolean) => {
    if (val) {
        form.data = {
            ...detail.value
        }
        getData()
        local.getdroneOPeratorList()
    } else {
        destroy()

    }
})
watch(progressList, () => {
    createLayer()
})
const destroy = () => {
    scene.value && scene.value?.destroy()
    scene.value = null;
    setTimeout(() => {
        form.mounted = false
        nextTick(() => {
            form.mounted = true
        })
    }, 500);
}
onBeforeUnmount(() => {
    destroy()
})
let timer: any
let speedVal = ref(1)
const start = () => {
    // 第一次end是防止重复点击开始的
    end(false)
    play.value = 1
    timer = setInterval(() => {
        if (progressIndex.value < (form.list.length - 1)) return progressIndex.value++
        progressIndex.value = 0
        end()
    }, Math.floor(500 / speedVal.value))
}
const end = (pause = true) => {
    pause && (play.value = 0)
    clearInterval(timer)
    timer = null
}
</script>
<style lang="less" scoped>
.box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;


    .playback {
        flex: 1;

        .track {
            position: relative;
            width: 100%;
            height: 100%;
            border-radius: 5px;
            overflow: hidden;
        }

        .info {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 350px;
            // height: 500px;
            background-color: var(--main-bg-color);
            border: 1px solid #e0dfdf;
            border-radius: 8px;
            z-index: 999;
            font-size: 14px;

            >.info-title {
                font-size: 16px;
                margin: 20px 20px 10px 20px;
                // color: #000;
            }

            >.info-demo {
                margin: 0 20px 10px 20px;

                >div {
                    margin-bottom: 10px;
                    display: flex;

                    >.name {
                        width: 120px;
                        color: #666;
                    }
                }
            }
        }

        .play-control {
            position: absolute;
            align-items: center;
            bottom: 60px;
            width: 100%;
            justify-content: center;
            display: flex;

            .button {
                display: flex;
                padding: 10px;
                margin-right: 20px;

                .play-strat {
                    padding: 20px;
                    background-color: rgb(var(--primary-6));
                    color: #fff;
                    cursor: pointer;
                    border-radius: 50%;
                }

                .play-pause {
                    padding: 20px;
                    background-color: rgb(var(--primary-6));
                    color: #fff;
                    cursor: pointer;
                    border-radius: 50%;
                }
            }

            .play-progress {
                display: flex;
                color: var(--color-text-1);

                .progress-value {
                    margin-left: 20px;
                    width: 130px;
                }
            }

            .progressDiv_speedDiv {
                height: 60px;
                display: flex;
                color: var(--color-text-1);

                :deep(.arco-select-view-single) {
                    background-color: unset !important;
                    color: var(--color-text-1) !important;
                }
            }
        }
    }

    .footer {
        width: 100%;
        display: flex;
        justify-content: right;
        padding-top: 16px;

    }
}
</style>